<template>
  <div class="shift-list">
    <div style="margin-bottom:12px; display:flex; gap:8px; align-items:center;">
      <el-button type="primary" @click="openAdd">新增班次</el-button>
      <el-tag type="info" effect="light">共 {{ rows.length }} 条</el-tag>
    </div>
    <el-table :data="rows" stripe @row-dblclick="openEdit">
      <el-table-column v-for="col in displayColumns" :key="col" :prop="col" :label="columnAliases[col]" show-overflow-tooltip>
        <template #default="{ row }">
          <template v-if="col === 'displayColor' || col === 'DisplayColor'">
            <span class="color-dot" :style="{ backgroundColor: String(row[col] || '').trim() }"></span>
            <span>{{ row[col] }}</span>
          </template>
          <template v-else>
            {{ renderCell(col, row) }}
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" text @click="openEdit(row)">编辑</el-button>
          <el-divider direction="vertical" />
          <el-button size="small" type="danger" text @click="confirmDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑班次' : '新增班次'" width="520px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="96px">
        <el-form-item label="班次名称" prop="shiftName">
          <el-input v-model="form.shiftName" placeholder="请输入班次名称" />
        </el-form-item>
        <el-form-item label="上班时间" prop="startTime">
          <el-time-picker v-model="form.startTime" placeholder="选择上班时间" format="HH:mm" value-format="HH:mm:ss" />
        </el-form-item>
        <el-form-item label="下班时间" prop="endTime">
          <el-time-picker v-model="form.endTime" placeholder="选择下班时间" format="HH:mm" value-format="HH:mm:ss" />
        </el-form-item>
        <el-form-item label="是否夜班" prop="isNightShift">
          <el-switch v-model="form.isNightShift" />
        </el-form-item>
        <el-form-item label="班次状态" prop="shiftStatus">
          <el-select v-model="form.shiftStatus" placeholder="请选择班次状态" style="width:100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="显示颜色" prop="displayColor">
          <el-select v-model="form.displayColor" placeholder="选择颜色" style="width:100%">
            <el-option v-for="c in colorOptions" :key="c.value" :label="c.label" :value="c.value">
              <span class="color-dot" :style="{ backgroundColor: c.value }"></span>
              <span>{{ c.label }} ({{ c.value }})</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="休息时长" prop="breakDuration">
          <el-input v-model="form.breakDuration" placeholder="例如 00:30:00" />
        </el-form-item>
        <el-form-item label="加班倍率" prop="overtimeRate">
          <el-input v-model.number="form.overtimeRate" placeholder="如 1 或 1.5" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

const rows = ref<any[]>([])
const columns = ref<string[]>([])
const client = getReadClient(1)
const write = getWriteClient(1)

const dialogVisible = ref(false)
const saving = ref(false)
const isEdit = ref(false)
const editingId = ref<string|number|undefined>(undefined)
const formRef = ref()
const form = ref<any>({ shiftStatus:1, isNightShift:false, displayColor:'#4CAF50' })
const rules = {
  shiftName: [{ required:true, message:'请输入班次名称', trigger:'blur' }],
  startTime: [{ required:true, message:'请选择上班时间', trigger:'change' }],
  endTime: [{ required:true, message:'请选择下班时间', trigger:'change' }],
  displayColor: [{ required:true, message:'请选择显示颜色', trigger:'change' }],
}
const colorOptions = [
  { label:'绿色', value:'#4CAF50' },
  { label:'蓝色', value:'#2196F3' },
  { label:'橙色', value:'#FF9800' },
  { label:'红色', value:'#F44336' },
  { label:'紫色', value:'#9C27B0' },
]

function openAdd(){
  isEdit.value = false
  editingId.value = undefined
  form.value = { shiftName:'', startTime:'', endTime:'', isNightShift:false, shiftStatus:1, displayColor:'#4CAF50', breakDuration:'00:30:00', overtimeRate:1 }
  dialogVisible.value = true
}

function openEdit(row:any){
  isEdit.value = true
  editingId.value = row?.shiftId ?? row?.ShiftId ?? row?.id ?? row?.Id
  form.value = {
    shiftName: row?.shiftName ?? row?.ShiftName ?? row?.name ?? '',
    startTime: row?.startTime ?? row?.StartTime ?? '',
    endTime: row?.endTime ?? row?.EndTime ?? '',
    isNightShift: row?.isNightShift ?? row?.IsNightShift ?? false,
    shiftStatus: Number(row?.shiftStatus ?? row?.ShiftStatus ?? 1),
    displayColor: (row?.displayColor ?? row?.DisplayColor ?? '#4CAF50'),
    breakDuration: row?.breakDuration ?? row?.BreakDuration ?? row?.breakduration ?? '00:30:00',
    overtimeRate: Number(row?.overtimeRate ?? row?.OvertimeRate ?? 1),
  }
  dialogVisible.value = true
}

// 删除（使用 GET）
async function confirmDelete(row:any){
  const id = row?.shiftId ?? row?.ShiftId ?? row?.id ?? row?.Id
  if(id === undefined || id === null){
    ElMessage.error('未找到可删除的 shiftId')
    return
  }
  try{
    await ElMessageBox.confirm('确认删除该班次吗？', '提示', { type:'warning', confirmButtonText:'删除', cancelButtonText:'取消' })
    await write.get('schedwrite/api/Team/DelShift', { params: { shiftId: id } })
    ElMessage.success('删除成功')
    const res = await client.get('schedread/api/Team/GetShift')
    const payload = res?.data
    const data = Array.isArray(payload) ? payload : (payload?.data ?? payload?.items ?? [])
    rows.value = Array.isArray(data) ? data : []
    columns.value = rows.value.length > 0 ? Object.keys(rows.value[0]) : []
  }catch(e:any){
    if(e !== 'cancel'){
      ElMessage.error(e?.message || '删除失败')
    }
  }
}

// 常见字段中文名称映射（存在则展示为中文，其他字段隐藏）
const columnAliases: Record<string, string> = {
  id: 'ID', Id: 'ID', shiftId: '班次ID', ShiftId: '班次ID',
  name: '班次名称', shiftName: '班次名称', ShiftName: '班次名称',
  startTime: '上班时间', StartTime: '上班时间', workStartTime: '上班时间', onDutyTime: '上班时间',
  endTime: '下班时间', EndTime: '下班时间', workEndTime: '下班时间', offDutyTime: '下班时间',
  isEnabled: '启用', IsEnabled: '启用', enabled: '启用',
  isOvertime: '加班', IsOvertime: '加班', isUrgentWorkday: '加班',
  remark: '备注', Remark: '备注',
  isNightShift: '是否夜班', IsNightShift: '是否夜班',
  displayColor: '显示颜色', DisplayColor: '显示颜色',
  overtimeRate: '加班倍率', OvertimeRate: '加班倍率',
  breakduration: '休息时长', breakDuration: '休息时长', BreakDuration: '休息时长',
  shiftStatus: '班次状态', ShiftStatus: '班次状态',
  isDelete: '已删除', IsDelete: '已删除',
}

// 仅显示有中文别名的列，且排除“已删除”列
const displayColumns = computed(()=>
  columns.value.filter(col => columnAliases[col] && columnAliases[col] !== '已删除')
)

function fmtBoolean(v:any){
  if (typeof v === 'boolean') return v ? '是' : '否'
  if (typeof v === 'number') return v === 1 ? '是' : '否'
  if (typeof v === 'string'){
    const t = v.trim().toLowerCase()
    if (t === 'true' || t === '1' || t === 'y') return '是'
    if (t === 'false' || t === '0' || t === 'n') return '否'
  }
  return v
}

function renderCell(prop:string, row:any){
  if (prop === 'isNightShift' || prop === 'IsNightShift'){
    return fmtBoolean(row?.[prop])
  }
  if (prop === 'shiftStatus' || prop === 'ShiftStatus'){
    const v = row?.[prop]
    if (v === 1 || v === '1') return '启用'
    if (v === 0 || v === '0') return '禁用'
    return v
  }
  return row?.[prop]
}

onMounted(async()=>{
  try{
    const res = await client.get('schedread/api/Team/GetShift')
    const payload = res?.data
    const data = Array.isArray(payload) ? payload : (payload?.data ?? payload?.items ?? [])
    rows.value = Array.isArray(data) ? data : []
    columns.value = rows.value.length > 0 ? Object.keys(rows.value[0]) : []
  }catch(err:any){
    ElMessage.error(err?.message || '获取班次失败')
  }
})

async function save(){
  try{
    // @ts-ignore
    await formRef.value?.validate()
    saving.value = true
    const payload:any = {
      shiftName: String(form.value.shiftName || ''),
      startTime: String(form.value.startTime || ''),
      endTime: String(form.value.endTime || ''),
      isNightShift: !!form.value.isNightShift,
      shiftStatus: Number(form.value.shiftStatus ?? 1),
      displayColor: String(form.value.displayColor || ''),
      breakDuration: String(form.value.breakDuration || ''),
      overtimeRate: Number(form.value.overtimeRate ?? 1),
    }
    if (isEdit.value){
      if (editingId.value === undefined || editingId.value === null){
        ElMessage.error('缺少有效的 shiftId，无法提交修改')
        return
      }
      payload.shiftId = editingId.value
      await write.post('/api/Team/UpdShift', payload)
      ElMessage.success('编辑成功')
    }else{
      await write.post('/api/Team/AddShift', payload)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    const res = await client.get('schedread/api/Team/GetShift')
    const payloadRes = res?.data
    const data = Array.isArray(payloadRes) ? payloadRes : (payloadRes?.data ?? payloadRes?.items ?? [])
    rows.value = Array.isArray(data) ? data : []
    columns.value = rows.value.length > 0 ? Object.keys(rows.value[0]) : []
  }catch(e:any){
    ElMessage.error(e?.message || (isEdit.value ? '编辑失败' : '新增失败'))
  }finally{
    saving.value = false
  }
}
</script>

<style scoped>
.shift-list { padding: 20px; }
.color-dot{ display:inline-block; width:14px; height:14px; border-radius:4px; border:1px solid #e5e7eb; margin-right:6px; vertical-align:middle; }
</style>
